package cn.edu.nuaa.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
    private static final String ALGORITHM = "MD5";
    private static final int BUFFER_SIZE = 8192;

    public static String calculateMD5(File file) throws NoSuchAlgorithmException, IOException {
        // 获取 MD5 消息摘要实例
        MessageDigest md = MessageDigest.getInstance(ALGORITHM);
        try (DigestInputStream dis = new DigestInputStream(new FileInputStream(file), md)) {
            byte[] buffer = new byte[BUFFER_SIZE];
            while (dis.read(buffer) != -1) {}
        }
        byte[] hash = md.digest(); // 计算散列值
        StringBuilder sb = new StringBuilder();
        for (byte b : hash) {
            sb.append(String.format("%02x", b)); // 转为16进制字符串
        }
        return sb.toString();
    }
}
